package com.slipper.handler;

import com.slipper.exception.CommonException;
import com.slipper.exception.DecryptException;
import com.slipper.exception.ForbiddenException;
import com.slipper.exception.NotLoginException;
import com.slipper.util.ResultUtil;
import com.slipper.util.Tool;
import org.apache.ibatis.exceptions.PersistenceException;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletResponse;
import java.net.SocketTimeoutException;

@RestController
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    @ExceptionHandler(value = Throwable.class)
    public String exceptionHandler(HttpServletResponse response, Exception e) {
        Throwable throwable = e;
        String message = null;
        if (throwable instanceof NotLoginException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 未登录
            message = "登录超时/未登录。";
        } else if (throwable instanceof ForbiddenException) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 拒绝访问
        } else if (throwable instanceof NoHandlerFoundException) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 找不到资源
        } else if (throwable instanceof SocketTimeoutException) {
            response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT); // 请求超时
        } else if (throwable instanceof MyBatisSystemException) {
            throwable = e.getCause() != null ? e.getCause() : e;
            if (throwable instanceof PersistenceException) {
                throwable = throwable.getCause() != null ? throwable.getCause() : e;
            }
        } else if (throwable instanceof DecryptException) {
            message = "数据解释失败，请刷新页面或者重新登录。";
        } else if (!(throwable instanceof CommonException) && throwable != null) {
            throwable = e.getCause() != null ? e.getCause() : e;
        }

        if (throwable instanceof RuntimeException) {
            message = throwable.getMessage();
        }
        message = Tool.isNotBlank(message) ? message : "服务器内部错误！";
        logger.error("调用发生异常！", throwable);

        response.setHeader("Content-Disposition", null);
        response.setContentType("application/json;charset=UTF-8");
        return ResultUtil.failureResult(message);
    }

    @RequestMapping("/error/notLogin")
    public String notLoginError(HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 拒绝访问
        return ResultUtil.failureResult("未登录！");
    }

    @RequestMapping("/error/forbidden")
    public String forbiddenError(HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 拒绝访问
        return ResultUtil.failureResult("权限不足！");
    }
}